package be.cgi.heroesmanager.activities;

import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import be.cgi.heroesmanager.R;
import be.cgi.heroesmanager.db.HeroesAdapter;

public class MainActivity extends Activity {

	ListView lvHeroes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		checkForDBupdate();
		
		Configuration currentConfig = getResources().getConfiguration();
		currentConfig.locale = new Locale(Locale.FRANCE.toString());
		getResources().updateConfiguration(currentConfig,getResources().getDisplayMetrics());

		lvHeroes = (ListView) findViewById(R.id.lvHeroes);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		HeroesAdapter adap = new HeroesAdapter(getApplicationContext());
		adap.openReadable();
		Cursor c = adap.getAllCursor();
		adap.close();

		String[] from = { HeroesAdapter.COLUMN_NAME, HeroesAdapter.COLUMN_CITY };

		int[] to = { R.id.text1, R.id.text2 };

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				getApplicationContext(), R.layout.heroes_list_item,
				c, from, to)
		{
		    @Override
		    public View getView(int position, View convertView, ViewGroup parent)
		    {
		        final View row = super.getView(position, convertView, parent);
		        
		        
		        
		        return row;
		    }
		};
		
		lvHeroes.setAdapter(adapter);
		
		lvHeroes.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> lv, View v, int position,
					long id) {
				Intent intent = new Intent(getApplicationContext(), DetailsActivity.class);
				intent.putExtra(HeroesAdapter.COLUMN_ID, id);
				startActivity(intent);				
			}
		});
	}
	
	public void btnAdd_onClick(View v){
		Intent intent = new Intent(getApplicationContext(), AddActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void checkForDBupdate() {
		HeroesAdapter adap = new HeroesAdapter(getApplicationContext());
		adap.openReadable();
		adap.close();
	}

}
